package com.jinmdz.fmis.common.util.third;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Hashtable;

/**
 * zxing工具类
 *
 * @author LiCongLu
 * @date 2020-01-07 15:46
 */
public final class QrCodeUtil {

    /**
     * 二维码大小
     */
    public static final int QRCodeSize = 500;

    /**
     * 生成二维码
     *
     * @param contents 二维码内容
     * @param format   图片格式
     * @param path     图片生成路径
     * @return
     * @author LiCongLu
     * @date 2020-01-07 15:53
     */
    public static void writeToPath(String contents, String format, Path path) throws WriterException, IOException {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 2);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, QRCodeSize, QRCodeSize, hints);
        MatrixToImageWriter.writeToPath(bitMatrix, format, path);
    }
}
